<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>生成故事 - AI故事生成器</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href='/static/css/1.css'>
    <link rel="stylesheet" href="/static/css/header.css">
    <link rel="stylesheet" href="/static/css/footer.css">
    <link rel="stylesheet" href="/static/css/generate.css">
    <script src="/static/js/header.js" defer></script>
</head>
<body>
<!-- 导航栏 -->
{% include 'header.html' %}

<main class="container">
    <h1>生成您的故事</h1>

    <!-- 错误消息显示 -->
    <div id="error-message" class="error-message"></div>
    <div id="success-message" class="success-message"></div>

    <form id="story-form" method="POST" action="{% url 'store_system:generate_story' %}">
        {% csrf_token %}
        <div class="generator-form">
            <div class="form-group">
                <label for="keywords">关键词</label>
                <input type="text" id="keywords" name="keywords" placeholder="输入故事关键词，用逗号分隔"
                       value="{{ keywords|default:'' }}" required>
            </div>
            <div class="form-group">
                <label for="genre"><i class="fas fa-book icon"></i> 故事类型</label>
                <select id="genre" name="genre" required>
                    <option value="">请选择故事类型</option>
                    {% for category in categories %}
                        <option value="{{ category.id }}"
                                {% if genre == category.id|stringformat:"s" %}selected{% endif %}>
                            {{ category.name }}
                        </option>
                    {% endfor %}
                </select>
            </div>
            <div class="form-group">
                <label for="length">故事长度</label>
                <select id="length" name="length">
                    <option value="short" {% if length == 'short' %}selected{% endif %}>短篇（500字左右）</option>
                    <option value="medium" {% if length == 'medium' %}selected{% endif %}>中篇（1000字左右）</option>
                    <option value="long" {% if length == 'long' %}selected{% endif %}>长篇（2000字以上）</option>
                </select>
            </div>
            <button type="submit" class="btn btn_generate btn-primary" id="generate-btn">生成故事</button>
        </div>
    </form>

    <div id="loading">
        <div class="spinner"></div>
        <p>AI正在努力创作中，请稍候...</p>
    </div>

    {% if generated_story %}
        <div class="result-area" style="display: block;">
            <h2>您的故事已生成</h2>
            <div class="story-result">
                <h3>{{ generated_story.title }}</h3>
                <p>{{ generated_story.content }}</p>
            </div>
            <div class="action-buttons">
                <button class="btn btn-primary" onclick="saveStory()">保存故事</button>
                <button class="btn" onclick="window.location.reload()">重新生成</button>
                <button class="btn" onclick="shareStory()">分享</button>
                <button class="btn btn-secondary" onclick="enableEdit()">编辑故事</button>
            </div>
        </div>
    {% else %}
        <div class="result-area" style="display: none;">
            <h2>您的故事已生成</h2>
            <div class="story-result">
                <!-- 生成的故事内容将显示在这里 -->
            </div>
            <div class="action-buttons">
                <button class="btn btn-primary" onclick="saveStory()">保存故事</button>
                <button class="btn" onclick="window.location.reload()">重新生成</button>
                <button class="btn" onclick="shareStory()">分享</button>
                <button class="btn btn-secondary" onclick="enableEdit()">编辑故事</button>
            </div>
        </div>
    {% endif %}
</main>

<!-- 页脚 -->
{% include 'footer.html' %}

<script>
    // 表单提交处理
    document.getElementById('story-form').addEventListener('submit', function (e) {
        e.preventDefault();

        // 隐藏之前的消息
        document.getElementById('error-message').style.display = 'none';
        document.getElementById('success-message').style.display = 'none';

        // 验证表单
        const keywords = document.getElementById('keywords').value;
        if (!keywords.trim()) {
            showError('请输入故事关键词');
            return;
        }

        // 显示加载动画
        document.getElementById('loading').style.display = 'block';
        document.querySelector('.result-area').style.display = 'none';

        // 使用AJAX提交表单
        const formData = new FormData(this);

        fetch(this.action, {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
            .then(response => response.json())
            .then(data => {
                // 隐藏加载动画
                document.getElementById('loading').style.display = 'none';

                if (data.success) {
                    // 显示生成的故事
                    const resultArea = document.querySelector('.result-area');
                    const storyResult = document.querySelector('.story-result');

                    storyResult.innerHTML = `
                        <h3>${data.story.title}</h3>
                        <p>${data.story.content}</p>
                    `;

                    resultArea.style.display = 'block';

                    // 保存故事数据到全局变量，供保存功能使用
                    window.currentStory = data.story;
                } else {
                    showError(data.message || '生成故事失败，请重试');
                }
            })
            .catch(error => {
                document.getElementById('loading').style.display = 'none';
                console.error('Error:', error);
                showError('生成故事时发生错误，请检查网络连接');
            });
    });

    // 显示错误消息
    function showError(message) {
        const errorDiv = document.getElementById('error-message');
        errorDiv.textContent = message;
        errorDiv.style.display = 'block';
    }

    // 显示成功消息
    function showSuccess(message) {
        const successDiv = document.getElementById('success-message');
        successDiv.textContent = message;
        successDiv.style.display = 'block';
    }

  // 保存故事函数
function saveStory() {
    if (!window.currentStory) {
        showError('没有可保存的故事');
        return;
    }

    // 获取分类ID
    const genreId = window.currentStory.genre || document.getElementById('genre').value;

    // 准备保存的数据
    const storyData = {
        title: window.currentStory.title,
        content: window.currentStory.content,
        genre: genreId,
        keywords: window.currentStory.keywords || document.getElementById('keywords').value
    };

    fetch('{% url "store_system:save_story" %}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': getCookie('csrftoken'),
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify(storyData)
    })
    .then(response => {
        // 检查响应状态和内容类型
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const contentType = response.headers.get('content-type');
        if (!contentType || !contentType.includes('application/json')) {
            return response.text().then(text => {
                throw new Error(`Expected JSON but got: ${text.substring(0, 100)}...`);
            });
        }

        return response.json();
    })
    .then(data => {
        if (data.success) {
            showSuccess('故事保存成功！');
            // 更新当前故事ID（如果存在）
            if (data.story_id) {
                window.currentStory.id = data.story_id;
            }
        } else {
            showError('保存失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showError('保存故事时发生错误: ' + error.message);
    });
}

    // 分享故事函数
    function shareStory() {
        if (!window.currentStory) {
            showError('没有可分享的故事');
            return;
        }

        if (navigator.share) {
            navigator.share({
                title: window.currentStory.title,
                text: window.currentStory.content.substring(0, 100) + '...',
                url: window.location.href
            })
                .then(() => console.log('分享成功'))
                .catch(error => console.log('分享失败', error));
        } else {
            // 复制到剪贴板的备选方案
            const tempTextArea = document.createElement('textarea');
            tempTextArea.value = `${window.currentStory.title}\n\n${window.currentStory.content.substring(0, 200)}...\n\n查看完整故事: ${window.location.href}`;
            document.body.appendChild(tempTextArea);
            tempTextArea.select();
            document.execCommand('copy');
            document.body.removeChild(tempTextArea);
            showSuccess('故事链接已复制到剪贴板，可以粘贴分享');
        }
    }

    // 启用编辑模式
    function enableEdit() {
        const resultArea = document.querySelector('.result-area');
        const storyResult = document.querySelector('.story-result');

        // 切换到编辑模式
        resultArea.classList.add('edit-mode');

        // 获取当前故事内容
        const title = storyResult.querySelector('h3').textContent;
        const content = storyResult.querySelector('p').textContent;

        // 替换为编辑表单
        storyResult.innerHTML = `
            <input type="text" class="edit-title" value="${title}" placeholder="故事标题">
            <textarea class="edit-content" placeholder="故事内容">${content}</textarea>
            <div class="edit-buttons">
                <button class="btn btn-primary" onclick="saveEditedStory()">保存修改</button>
                <button class="btn" onclick="cancelEdit()">取消</button>
            </div>
        `;
    }

    // 取消编辑
    function cancelEdit() {
        const resultArea = document.querySelector('.result-area');
        const storyResult = document.querySelector('.story-result');

        // 退出编辑模式
        resultArea.classList.remove('edit-mode');

        // 恢复原始显示
        storyResult.innerHTML = `
            <h3>${window.currentStory.title}</h3>
            <p>${window.currentStory.content}</p>
        `;
    }

    // 保存编辑后的故事
    function saveEditedStory() {
        const editedTitle = document.querySelector('.edit-title').value;
        const editedContent = document.querySelector('.edit-content').value;

        if (!editedTitle.trim() || !editedContent.trim()) {
            showError('标题和内容不能为空');
            return;
        }

        // 更新当前故事
        window.currentStory.title = editedTitle;
        window.currentStory.content = editedContent;

        // 退出编辑模式并更新显示
        const resultArea = document.querySelector('.result-area');
        resultArea.classList.remove('edit-mode');

        const storyResult = document.querySelector('.story-result');
        storyResult.innerHTML = `
            <h3>${editedTitle}</h3>
            <p>${editedContent}</p>
        `;

        showSuccess('故事已更新');
    }

    // 获取CSRF token的辅助函数
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
</script>
</body>
</html>